<template>
  <div>
    <el-card class="box-card" style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span>加密</span>
      </div>
      <div>
        <el-form-item label="原文">
        <el-input type="textarea" v-model="form.src"></el-input>
      </el-form-item>
      <el-form-item label="密文">
        <el-input type="textarea" v-model="form.toEnc"></el-input>
      </el-form-item>
      </div>
    </el-card>
    <el-card class="box-card"  style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span>解密</span>
      </div>
      <div>
        <el-form-item label="密文">
        <el-input type="textarea" v-model="form.enc"></el-input>
      </el-form-item>
      <el-form-item label="原文">
        <el-input type="textarea" v-model="form.toSrc"></el-input>
      </el-form-item>
      </div>
    </el-card>
  </div>
</template>

<script>
import { sm4Dec, sm4Enc } from '../../utils/crypto_sm4'
export default {
  name: 'Sm4ToolAll',
  components: {},
  props: {
    encKey: {
      required: true
    }
  },
  data () {
    return {
      form: {
        src: '',
        toEnc: '',
        enc: '',
        toSrc: ''
      }
    }
  },
  watch: {
    'form.src': {
      handler (newValue, oldVal) {
        this.enc()
      },
      deep: false // 深度监听
    },
    'form.enc': {
      handler (newValue, oldVal) {
        this.dec()
      },
      deep: false // 深度监听
    }
  },
  computed: {},
  methods: {
    enc () {
      if (this.encKey && this.form.src) {
        this.form.toEnc = sm4Enc(this.form.src, this.encKey)
      }
    },
    dec () {
      if (this.encKey && this.form.enc) {
        try {
          let toSrc = sm4Dec(this.form.enc, this.encKey)
          if (toSrc) {
            this.form.toSrc = toSrc
          } else {
            this.form.toSrc = '解密失败'
          }
        } catch (error) {
          this.form.toSrc = '解密失败'
          console.error(error)
        }
      }
    }
  },
  created () {},
  mounted () {}
}
</script>
<style lang="less" scoped>
</style>
